package com.kaoyaya.delivery.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ExpandableListView.OnGroupExpandListener;

import com.googlecode.androidannotations.annotations.AfterViews;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.EFragment;
import com.googlecode.androidannotations.annotations.ViewById;
import com.kaoyaya.delivery.activity.R;
import com.kaoyaya.delivery.activity.SlidingActivity;
import com.kaoyaya.delivery.adapter.DeliveryRecordAdapter;
import com.kaoyaya.delivery.data.Constants;
import com.kaoyaya.delivery.data.DataHelper;
import com.kaoyaya.delivery.data.entity.DeliveryRecord;
import com.kaoyaya.delivery.data.entity.OrderItem;
import com.kaoyaya.delivery.data.entity.Result;
import com.kaoyaya.util.CommUtil;

@EFragment(R.layout.fmt_delivery_record)
public class DeliveryRecordFmt extends Fragment {

	@ViewById TextView tvTitle;
	@ViewById ExpandableListView elvDelRecord;
	@Bean DataHelper dataHelper;
	DeliveryRecordAdapter deliveryRecordAdapter;
	SlidingActivity activity;
	Dialog pgDialog;
	
	// 更多布局
	LinearLayout llMore;
	ProgressBar pbMore;
	TextView tvMore;
	boolean hasMore;
	int lastIndex, count, pageIndex, groupPosition;
	
	final int IS_DELIVERY_RECORD = 0, IS_REDELIVERY = 1, IS_REFUND = 2, IS_RECORD_CHIRLD = 3;
	
	@AfterViews
	void initView() {
		this.activity = (SlidingActivity) getActivity();
		tvTitle.setText("发货管理");
		
		dataHelper.setCallbackHandler(callbackHandler);
		initRecord();
		
		View vMore = LayoutInflater.from(activity).inflate(R.layout.more_data_bar, null);
		llMore = (LinearLayout) vMore.findViewById(R.id.llMore);
		llMore.setVisibility(View.GONE);
		pbMore = (ProgressBar) vMore.findViewById(R.id.pbMore);
		tvMore = (TextView) vMore.findViewById(R.id.tvMore);
		llMore.setOnClickListener(clickListener);
		elvDelRecord.addFooterView(vMore);
		elvDelRecord.setOnScrollListener(scrollListener);
		elvDelRecord.setOnGroupExpandListener(groupExpandListener);
	}
	
	OnGroupExpandListener groupExpandListener = new OnGroupExpandListener() {

		@Override
		public void onGroupExpand(int groupPosition) {
			for (int i = 0; i < deliveryRecordAdapter.getGroupCount(); i++) {
				if (groupPosition != i) {
					elvDelRecord.collapseGroup(i);
				}
			}
			if (deliveryRecordAdapter.getGroup(groupPosition).getOrder().isEmpty()) {
				DeliveryRecordFmt.this.groupPosition = groupPosition;
				pgDialog.show();
				dataHelper.getDeliveryRecordOrder(IS_RECORD_CHIRLD, deliveryRecordAdapter.getGroup(groupPosition).getOrderNo());
			}
		}
		
	};
	
	void initRecord() {
		pgDialog = CommUtil.createLoadingDialog(activity, null);
		lastIndex = 0; count = 0; pageIndex = 0;
		deliveryRecordAdapter = null;
		dataHelper.getDeliveryRecords(IS_DELIVERY_RECORD, pageIndex);
	}
	
	void initRecordData(List<DeliveryRecord> records) {
		if (deliveryRecordAdapter == null) {
			deliveryRecordAdapter = new DeliveryRecordAdapter(getActivity(), new ArrayList<DeliveryRecord>(), clickListener);
			elvDelRecord.setAdapter(deliveryRecordAdapter);
		}
		int size = records.size();
		for (DeliveryRecord deliveryRecord : records) {
			deliveryRecord.setOrder(new ArrayList<OrderItem>());
		}
		count += size;
		deliveryRecordAdapter.addRecord(records);
		deliveryRecordAdapter.notifyDataSetChanged();
		hasMore = size < Constants.PAGE_DEFAULT_SIZE ? false : true;
		if (count > 0) {
			tvMore.setText(hasMore ? "加载更多..." : "总共" + count + "个记录");
			pbMore.setVisibility(View.GONE);
			llMore.setVisibility(View.VISIBLE);
		} else {
			Toast.makeText(activity, "没有获取到对应的数据!", Toast.LENGTH_SHORT).show();
		}
	}
	
	void initRecordOrderData(List<OrderItem> orderItems) {
		deliveryRecordAdapter.getGroup(groupPosition).setOrder(orderItems);
		deliveryRecordAdapter.notifyDataSetChanged();
	}
	
	void nextPage() {
		if (hasMore) {
			pbMore.setVisibility(View.VISIBLE);
			tvMore.setText("数据正在加载，请稍候...");
			pageIndex++;
			dataHelper.getDeliveryRecords(IS_DELIVERY_RECORD, pageIndex);
		}
	}
	
	OnScrollListener scrollListener = new OnScrollListener() {

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			lastIndex = firstVisibleItem + visibleItemCount - 1;
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (hasMore && lastIndex == deliveryRecordAdapter.getGroupCount() && scrollState == OnScrollListener.SCROLL_STATE_FLING) {
				nextPage();
			}
		}
		
	};
	
	View.OnClickListener clickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.llMore:
				nextPage();
				break;
			case R.id.btnRedelivery:
				DeliveryRecord record = (DeliveryRecord) v.getTag();
				dataHelper.reSendMail(IS_REDELIVERY, record.getOrderNo());
				break;
			case R.id.btnRefund:
				OrderItem orderItem = (OrderItem) v.getTag();
				dataHelper.refund(IS_REFUND, orderItem.getId());
				break;
			}
		}
	};
	
	@SuppressWarnings("unchecked")
	Handler callbackHandler = new Handler() {
		public void handleMessage(Message msg) {
			Object result = msg.obj;
			if (result != null) {
				switch (msg.what) {
				case IS_DELIVERY_RECORD:
					List<DeliveryRecord> records = (List<DeliveryRecord>) result;
					initRecordData(records);
					break;
				case IS_REDELIVERY:
					Result $result = (Result) result;
					if ($result.getResultCode() == 1) {
						Toast.makeText(activity, "恭喜你，重发成功！", Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(activity, "抱歉，操作失败！", Toast.LENGTH_SHORT).show();
					}
					break;
				case IS_REFUND:
					Result $result1 = (Result) result;
					if ($result1.getResultCode() == 1) {
						Toast.makeText(activity, "恭喜你，退款成功！", Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(activity, "抱歉，操作失败！", Toast.LENGTH_SHORT).show();
					}
					break;
				case IS_RECORD_CHIRLD:
					initRecordOrderData((List<OrderItem>) result);
					break;
				}
			} else {
				Toast.makeText(activity, "抱歉，操作失败！", Toast.LENGTH_SHORT).show();
			}
			if (pgDialog != null) {
				pgDialog.cancel();
			}
		}
	};
	
}
